<template>
  <div v-loading="loading" class="app-container">
    <el-steps :active="active">
      <el-step title=" " description="系统基本信息"></el-step>
      <el-step title=" " description="填写资源申请"></el-step>
      <el-step title=" " description="服务清单送审"></el-step>
    </el-steps>
    <AddA ref="adda" @next="next" :dept="configure.dept" v-show="active == 1" />
    <AddB
      ref="addb"
      @next="next"
      :configure="configure"
      :supplierCode="form.cloudUp.supplierCode"
      v-show="active == 2"
    />
    <AddC ref="addc" @upload="upload" :configure="configure" :form="form" v-show="active == 3" />
    <Process ref="process" :ind="0" style="margin-bottom: 10px" />
    <div style="display: flex; justify-content: flex-end">
      <el-button :loading="btnLoading" type="info" v-if="active > 1" @click="active--">上一步</el-button>
      <el-button :loading="btnLoading" type="primary" v-if="active == 3" @click="submitApply">提交审核</el-button>
      <el-button :loading="btnLoading" type="primary" v-else @click="next(false)">下一步</el-button>
      <el-button @click="ReturnSuperio">取 消</el-button>
    </div>
  </div>
</template>

<script>
import AddA from "./addA.vue";
import AddB from "./addB.vue";
import AddC from "./addC.vue";
import Process from "../../todoItem/todo/process.vue";
import { resourcesChangeApply } from "@/api/resources/change.js";
import { treeselect } from "@/api/system/dept";
import { getDicts } from "@/api/system/dict/data";
import { uploadFile } from "@/api/system/upload.js";
import { listByCode, serviceByClazz, classByCode, specEcs } from "@/api/resources/apply";
export default {
  name: "addChangesNoXc",
  components: {
    AddA,
    AddB,
    AddC,
    Process,
  },
  data() {
    return {
      loading: false,
      btnLoading: false,
      // 申请步骤
      active: 1,
      // 表单参数
      form: {
        //系统id
        cloudUpId: "",
        //系统基本信息
        cloudUp: {},
        cloudSupplier: "", //服务商
        cloudSupplier_label: "", //服务商名称
        hosts: [], //资源列表
        databases: [], //数据库列表
        storeProducts: [], //存储产品列表
        safeProducts: [], //安全产品列表
        remark: "", //说明
        files: [], //文件
        actionName: "发起申请",
      },
      //配置
      configure: {
        dept: [],
        available_domain: [], //可用域
        cloud_service_provider: [], //服务商
        storage_type: [], //系统盘类型
        codeList: [], //云服务器规格列表
        czxtList: [], //操作系统列表
        ccList: [], //数据盘类型
        fwcpList: [], //服务型磁盘类型
        wlfwqList: [], //高性能服务器资源类型
        sjkList: [], //数据库类型
        yyaqList: [], //安全产品,
        SpecificationsList: [],
      },
      subData: null,
    };
  },
  created() {
    setTimeout(() => {
      this.$refs.adda.xzfsChange(2);
      //   this.$refs.process.init({
      //     definitionName: '资源变更',
      //     taskName: '资源变更'
      //   })
    }, 100);
  },
  mounted() {
    setTimeout(() => {
      this.$refs.process.init({
        definitionName: "资源变更",
        taskName: "资源变更",
      });
    }, 100);
  },
  methods: {
    getDataOfAdd(supplierCode) {
      this.loading = true;
      // 获取信创CPU或者内存规格
      specEcs({ Inspur: supplierCode }).then((res) => {
        res.rows.push({
          specName: "自定义",
          cpuNumber: 0,
          cpuCode: "vcpu",
          memorySize: 4,
          memoryCode: "memory",
        });
        this.configure.SpecificationsList = res.rows;
      });
      //部门列表
      treeselect({}).then((response) => {
        this.configure.dept = response.data;
      });
      //可用域
      getDicts("available_domain").then((response) => {
        this.configure.available_domain = response.data;
      });
      //服务商
      getDicts("cloud_service_provider").then((response) => {
        this.configure.cloud_service_provider = response.data;
      });
      //盘类型
      serviceByClazz({ code: "cc", supplier: supplierCode }).then((response) => {
        response.data.forEach((item) => {
          if (["FCcc(tykcc)2", "FCcc_ssd", "spycc2"].indexOf(item.code) < 0) {
            this.configure.storage_type.push(item);
          }
          if (["spycc2"].indexOf(item.code) < 0) {
            this.configure.ccList.push(item);
          }
          if (["fbscc_wjcc2", "FCcc(tykcc)2", "FCcc_ssd"].indexOf(item.code) < 0) {
            this.configure.fwcpList.push(item);
          }
        });
      });
      //操作系统
      classByCode({ code: "czxt" }).then((response) => {
        this.configure.czxtList = response.data;
      });
      // //云服务器规格列表
      // listByCode("spec_ecs").then((response) => {
      //     this.configure.codeList = response.data;
      // });
      //高性能服务器资源类型列表
      serviceByClazz({ code: "wlfwq", supplier: supplierCode }).then((response) => {
        this.configure.wlfwqList = response.data;
      });
      //数据库类型列表
      serviceByClazz({ code: "sjk", supplier: supplierCode }).then((response) => {
        this.configure.sjkList = response.data;
      });
      //安全产品列表
      serviceByClazz({ code: "yyaq", supplier: supplierCode }).then((response) => {
        this.configure.yyaqList = response.data;
      });
      setTimeout(() => {
        this.loading = false;
      }, 100);
    },
    // 返回上级--> 资源申请列表
    ReturnSuperio() {
      this.$store.state.tagsView.visitedViews.splice(
        this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
        1
      );
      this.$destroy("addChanges");
      this.$router.push("/resources/change");
    },
    //下一步
    next(data) {
      console.log(data, "wwww");
      if (data) {
        if (this.active == 1) {
          this.getDataOfAdd(data.supplierCode);
          this.$refs.addb.init(data);
          this.active = 2;
        } else if (this.active == 2) {
          this.subData = data;
          this.$refs.addc.init(data);
          this.active = 3;
        }
      } else {
        if (this.active == 1) {
          this.$refs.adda.next();
        } else if (this.active == 2) {
          this.$refs.addb.next();
        }
      }
    },

    submitApply(data) {
      this.$confirm("是否确认提交变更?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.btnLoading = true;
        this.$refs.addc.childUpload();
        // return
        // resourcesChangeApply({ formObject: form }).then(res=>{
        //     if(res.code == 200){
        //         this.$store.state.tagsView.visitedViews.splice(this.$store.state.tagsView.visitedViews.findIndex(item => item.path === this.$route.path), 1)
        //         this.$destroy(this.$options.name)
        //         this.$router.push('/cloud/cloudapply')
        //     }
        // }).finally(res=>{
        //   this.btnLoading=false
        // })
      });
    },
    upload(files) {
      if (files) {
        let form = JSON.parse(JSON.stringify(this.subData));
        form.files = files;
        let safeProducts = [],
          hosts = [],
          storeProducts = [],
          databases = [];
        form.safeProductsList.forEach((item) => {
          if (parseInt(item.num) > 0) {
            if (parseInt(item.num) > parseInt(item.ysnum)) {
              let it = form.safeProducts[item.productName][0];
              for (let i = 0; i < item.num; i++) {
                if (i < item.ysnum) {
                  safeProducts.push(form.safeProducts[item.productName][i]);
                } else {
                  safeProducts.push({ ...it, id: "" });
                }
              }
            } else {
              for (let i = 0; i < item.ysnum; i++) {
                if (i >= item.num) {
                  form.safeProducts[item.productName][i].insStatus = "REMOVE";
                }
                safeProducts.push(form.safeProducts[item.productName][i]);
              }
            }
          }
        });
        console.log(form.safeProductsList, safeProducts, "--------------");
        form.hosts.forEach((item) => {
          if (item.insStatus) {
            hosts.push(item);
          }
        });
        form.storeProducts.forEach((item) => {
          if (!item.insStatus || item.insStatus != "REMOVE") {
            storeProducts.push(item);
          }
        });
        form.databases.forEach((item) => {
          if (item.insStatus) {
            databases.push(item);
          }
        });

        form.safeProducts = safeProducts;
        form.hosts = hosts;
        form.storeProducts = storeProducts;
        form.databases = databases;
        delete form.safeProductsList;
        this.sub(form);
      } else {
        this.btnLoading = true;
      }
    },

    /** 提交申请 */
    submitApply1() {
      this.$confirm("是否确认提交?", "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      }).then(() => {
        this.btnLoading = true;
        let form = JSON.parse(JSON.stringify(this.subData));
        if (this.form.files && this.form.files.length) {
          var param = new FormData();
          param.append("key", "file");
          this.form.files.forEach((item) => {
            param.append("file", item.raw);
          });
          if (this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw) {
            var cloudUpparam = new FormData();
            cloudUpparam.append("key", "file");
            this.form.cloudUp.files.forEach((item) => {
              cloudUpparam.append("file", item.raw);
            });
            uploadFile(cloudUpparam)
              .then((ress) => {
                form.cloudUp.files = ress.data;
                uploadFile(param)
                  .then((res) => {
                    form.files = res.data;
                    form.actionName = "发起申请";
                    this.sub(form);
                  })
                  .catch((e) => {
                    this.btnLoading = false;
                  });
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          } else {
            uploadFile(param)
              .then((res) => {
                form.files = res.data;
                form.actionName = "发起申请";
                this.sub(form);
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          }
        } else {
          if (this.form.cloudUp.files && this.form.cloudUp.files.length && this.form.cloudUp.files[0].raw) {
            var cloudUpparam = new FormData();
            cloudUpparam.append("key", "file");
            this.form.cloudUp.files.forEach((item) => {
              cloudUpparam.append("file", item.raw);
            });
            uploadFile(cloudUpparam)
              .then((res) => {
                form.cloudUp.files = res.data;
                form.actionName = "发起申请";
                this.sub(form);
              })
              .catch((e) => {
                this.btnLoading = false;
              });
          } else {
            form.actionName = "发起申请";
            this.sub(form);
          }
        }
      });
    },
    sub(form) {
      console.log(form, "errerere");
      let data = {
        cloudUpId: form.id,
        files: form.files,
        hosts: [],
        databases: [],
        storeProducts: [],
        safeProducts: [],
      };
      form.hosts.forEach((item) => {
        item.insId = item.id;
        //   delete item.id
        if (item.osDisk) {
          item.osDisk.insId = item.osDisk.id;
          // delete item.osDisk.id
        }
        item.disks.forEach((it) => {
          it.insId = it.id;
          // delete it.id
        });
        data.hosts.push({ changeTo: item });
      });
      form.databases.forEach((item) => {
        item.insId = item.id;
        //   delete item.id
        data.databases.push({ changeTo: item });
      });
      form.storeProducts.forEach((item) => {
        item.insId = item.id;
        //   delete item.id
        data.storeProducts.push({ changeTo: item });
      });
      form.safeProducts.forEach((item) => {
        item.insId = item.id;
        //   delete item.id
        data.safeProducts.push({ changeTo: item });
      });
      data.isXc = false;
      resourcesChangeApply({ formObject: data })
        .then((res) => {
          this.$message({
            message: "提交成功",
            type: "success",
          });
          this.$store.state.tagsView.visitedViews.splice(
            this.$store.state.tagsView.visitedViews.findIndex((item) => item.path === this.$route.path),
            1
          );
          this.$router.push("/resources/change");
        })
        .finally(() => {
          this.btnLoading = false;
        });
    },
  },
};
</script>
